package hzh;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.*;

public class LoginServlet  extends HttpServlet {

    private static String DB_URL    = "jdbc:mysql://127.0.0.1:3306/MyDB";
    private static String DB_USER   = "root";
    private static String DB_PASS   = "5201314huang";
    private static final long serialVersionUID = 1198763434511986380L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String user = request.getParameter("name");
        String pass = request.getParameter("password");
        String imgsrc1=request.getParameter("verifyInput");
        boolean flag = false;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try(Connection c = DriverManager.getConnection(DB_URL,DB_USER,DB_PASS);
            Statement s = c.createStatement()){

            String sql = "select * from users where user_id = '" + user +"' and user_password = '" + pass+"'";
            ResultSet rs = s.executeQuery(sql);
            HttpSession cuthcode=request.getSession();
            String imgsrc2= (String)cuthcode.getAttribute(AuthFilter.LOGIN_VALIDATE_CODE);
            if(rs.next())
                if(imgsrc1.equals(imgsrc2)){
                    flag = true;
                }
            else {
                flag=false;
                }
            else
                flag = false;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(flag==true){
            response.sendRedirect("./charge.jsp");
        }else {
            response.sendRedirect("./login.jsp");
        }
//
//        if (user != null && pass != null) {
//            if (user.equals("admins") && pass.equals("123456")) {
//                response.sendRedirect("./list");
//            } else {
//                response.sendRedirect("./login.html");
//            }
//        }
    }
}
